# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/1/23
# @File   : TX04_Last1YearTaxRefundAmt_SC.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:最近1年内应补退税额之和
code:TX04_Last1YearTaxRefundAmt_SC
tableName:
columnName:
groups:税务模块
dependencies:TX_SC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import pandas as pd
from collections import OrderedDict
from dateutil.relativedelta import relativedelta
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

last_month_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=i)).strftime('%Y%m%d')[:6] \
                    for i in range(1, 16)]

def getTable(table_Name):
    '''
    获取表
    :param x:
    :return:
    '''
    try:
        ic_data = TX_SC_DSJ['data'].get(table_Name)
        if ic_data in null_type_list:
            return None
        else:
            return ic_data if isinstance(ic_data, list) and len(ic_data) > 0 else [{}]
    except:
        return None

def isfloat(x):
    '''
    判断x为float类型
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float):
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True', 'NAN', 'nan',
                     'False', '-inf', '-INF', '-INFINITY', '-infinity', 'NaN', 'Nan']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def formatDate(time):

    import re
    import datetime
    try:
        r = re.compile(r'\D')
        tmp = r.sub('', time)
        if tmp.isdigit():
            date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
            return date
        else:
            return None
    except:
        return None


def TX04_Last1YearTaxRefundAmt():
    try:
        syptQysdsA1 = getTable('syptQysdsA1')
        if syptQysdsA1 == [{}] or syptQysdsA1 == None:
            return u'缺失值'
        else:
            # monthToday = datetime.datetime.now().year * 12 + datetime.datetime.now().month
            # monthOneYearAgo = (datetime.datetime.now().year - 1) * 12 + datetime.datetime.now().month
            amt_list = OrderedDict()
            for k in last_month_list:
                amt_list.update({k:'None'})
            # amt = {}
            # flag = []
            for i in syptQysdsA1:
                QSRQ = i.get('skssqq')
                QZRQ = i.get('skssqz')
                if QSRQ in null_type_list or QZRQ in null_type_list or formatDate(QSRQ) == None or formatDate(QZRQ) == None:
                    pass
                else:
                    Mons = (int(QZRQ[:4])-int(QSRQ[:4]))*12 + (int(QZRQ[5:7])-int(QSRQ[5:7]))
                    tmp = i.get('BQSJYBTSDSE')
                    if(Mons>=0):
                        if tmp in null_type_list:
                            pass
                        else:
                            tmp_Ave = round(float(tmp)/(Mons+1),6)
                            for j in range(Mons+1):
                                NDYF = datetime.datetime.strptime(QZRQ,'%Y-%m-%d') - relativedelta(months=j)
                                ND = str(NDYF)[:4]
                                YF = str(NDYF)[5:7]
                                key = str(ND) + str(YF)
                                if amt_list.get(key) == 'None':
                                    amt_list.update({key: tmp_Ave})
                                else:
                                    pass
                    else:
                        pass
            CountNone = 0
            amt_list_Value = amt_list.values()
            for m in range(len(amt_list_Value)):
                if amt_list_Value[m] ==  'None':
                    CountNone += 1
                else:
                    pass
            if CountNone == 15:
                return u'缺失值'
            else:
                amt_list_Value1 = amt_list.values()
                amt_list_Value2 = amt_list.values()
                for k in range(len(amt_list_Value1)):
                    if amt_list_Value2[k] ==  'None':
                        amt_list_Value2[k] = 0
                if amt_list_Value1[0] != 'None':
                    amt_sum = round(sum(amt_list_Value2[0:12]),4)
                elif amt_list_Value1[0] == 'None' and amt_list_Value1[1] != 'None':
                    amt_sum = round(sum(amt_list_Value2[1:13]),4)
                elif amt_list_Value1[0] == 'None' and amt_list_Value1[1] == 'None' and amt_list_Value1[2] != 'None':
                    amt_sum = round(sum(amt_list_Value2[2:14]),4)
                else:
                    amt_sum = round(sum(amt_list_Value2[3:15]),4)
                return amt_sum
    except:
        return u'缺失值'

result = TX04_Last1YearTaxRefundAmt()